<template>
  <view class="container">
    <up-form
				labelPosition="top"
				labelWidth="100%"
				:model="userInfo"
				:rules="rules"
				ref="uFormRef"
		>
			<up-form-item label="旧密码" prop="original_password">
				<up-input type="password" v-model="userInfo.original_password" placeholder="请输入旧密码"></up-input>
			</up-form-item>
			<up-form-item label="新密码" prop="password">
				<up-input type="password" v-model="userInfo.password" placeholder="请输入新密码"></up-input>
			</up-form-item>
			<up-form-item label="确认密码" prop="confirm_password">
				<up-input type="password" v-model="userInfo.confirm_password" placeholder="请输入确认密码"></up-input>
			</up-form-item>
    </up-form>
    <up-button class="mt-[30px]" type="primary" @click="submit">确认修改密码</up-button>
  </view>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import { updatePasswordApi } from '../../api';
import { redirect } from '@/utils/common';

const userInfo = ref({
  original_password: '',
  password: '',
  confirm_password: ''
})

const rules = {  
  'original_password': {  
    type: 'string',  
    required: true,  
    message: '请请输入旧密码',  
    trigger: ['blur', 'change'],  
  },  
  'password': [
    {  
      type: 'string',  
      required: true,  
      message: '请请输入新密码',  
      trigger: ['blur', 'change'],  
    },
    {
			// 自定义验证函数，见上说明
			validator: (rule:any, value:any, callback:any) => {
        if (userInfo.value.confirm_password && value !== userInfo.value.confirm_password) {
					return false;
				}
				return true;
			},
			message: '两次密码不一致',
			// 触发器可以同时用blur和change
			trigger: ['blur'],
		}
  ], 
  'confirm_password': [
    {  
      type: 'string',  
      required: true,  
      message: '请请输入确认密码',  
      trigger: ['blur', 'change'],  
    },
    {
			// 自定义验证函数，见上说明
			validator: (rule:any, value:any, callback:any) => {
        if (value !== userInfo.value.password) {
					return false;
				}
				return true;
			},
			message: '两次密码不一致',
			// 触发器可以同时用blur和change
			trigger: ['blur'],
		}
  ], 
}

const uFormRef = ref<any>(null);  
  
// 提交方法  
function submit() {  
  uFormRef.value?.validate().then(async (valid:boolean) => {  
    if (valid) {  
      const res = await updatePasswordApi(userInfo.value)
      if(res.code == 1) {
        uni.$u.toast('修改成功，请重新登录')
        setTimeout(() => {
          // 去登录
          redirect({
            url:"/addon/htscrm/pages/admin/login",
            mode: 'redirectTo'
          })
        }, 500);
      }
    } else {  
      uni.$u.toast('校验失败')
    }  
  }).catch(() => {  
    // 处理验证错误  
    uni.$u.toast('校验失败')
  });  
} 

</script>
<style lang="scss" scoped>
.container {
  background: #f7f7f7;
  min-height: 100vh;
  padding: 30rpx;
}
</style>